<?php

class Ajax extends Controller {
	
	function Ajax()
	{
		parent::Controller();	
	}
	
	function index()
	{
	}
	
	function orderMenu()
	{
		$this->load->database();
		
		@extract($_POST);
		$i = 0;
		foreach ($menu_list as $id){
			$data = array(
						'post_order' => $i,
						'post_menu' => 1
		            );
			$this->db->where('ID', $id);
			$this->db->update('gcms_posts', $data); 
			$i++;
			echo "$id ";
		}
	}	
	
	function orderOther()
	{
		$this->load->database();
		
		@extract($_POST);
		$i = 0;
		foreach ($other_list as $id){
			$data = array(
						'post_order' => $i,
						'post_menu' => 0
		            );
			$this->db->where('ID', $id);
			$this->db->update('gcms_posts', $data); 
			$i++;
			echo "$id ";
		}
	}	
	
	function deleteFile()
	{
		$file = $_POST['file'];
		$file = substr($file, 1, strlen($file));
		if(file_exists($file)){
			unlink($file);
			echo 'File '.$file.' deleted';
		}
	}
	
	function addFolder()
	{
		$this->load->helper('url');
		$this->load->helper('file');
		$this->load->helper('directory');
		$this->load->database();
		
		$dir = $_POST['dirname'];
		$dir = url_title($dir, 'underscore');
		
		//Check folder isn't same as page
		$error = false;
		$query = $this->db->query("SELECT * FROM gcms_posts");
		foreach ($query->result() as $row)
		{
			if($row->post_slug == $dir){ 
				$error = true;
			} 
		}
		
		if($dir != 'system' && $dir != 'themes' && !$error){
			mkdir($dir, 0777);
			echo 'Success';
		} else {
			echo 'Failed';
		}
	}
	
	function deleteFolder()
	{
		$this->load->helper('file');
		
		$dir = $_POST['dirname'];	
		$dir = trim($dir, '/');
		if($dir != "system" && $dir != "themes"){ //dont delete the system folder
			$this->_SureRemoveDir($dir, true);
			echo 'Success';
		} 
	}
	
	function _SureRemoveDir($dir, $DeleteMe) {
	    if(!$dh = @opendir($dir)) return;
	    while (false !== ($obj = readdir($dh))) {
	        if($obj=='.' || $obj=='..') continue;
	        if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
	    }

	    closedir($dh);
	    if ($DeleteMe){
	        @rmdir($dir);
	    }
	}
}
?>